<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="房东" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入房东名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系方式" prop="contact">
        <el-input
          v-model="queryParams.contact"
          placeholder="请输入联系方式"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="房东的id" prop="typeId">
        <el-input
          v-model="queryParams.typeId"
          placeholder="请输入房东的id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="评分" prop="score">
        <el-input
          v-model="queryParams.score"
          placeholder="请输入评分，1~5分，乘10保存，避免小数"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:owner:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:owner:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:owner:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:owner:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ownerList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="id" />
      <el-table-column label="房东名称" align="center" prop="name" />
      <el-table-column label="联系方式" align="center" prop="contact" />
      <el-table-column label="房东的id" align="center" prop="typeId" />
      <el-table-column label="房东图片，多个图片以','隔开" align="center" prop="images">
        <template #default="{ row }">
          <img
            v-if="getValidAvatar(row.images)"
            :src="getValidAvatar(row.images)"
            style="width:40px; height:40px; border-radius:6px;"
            alt="图片"
            @error="e => e.target.src = require('@/assets/images/profile.jpg')"
          />
        </template>
      </el-table-column>
      <el-table-column label="评分，1~5分，乘10保存，避免小数" align="center" prop="score" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:owner:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:owner:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改房东管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商铺名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入商铺名称" />
        </el-form-item>
        <el-form-item label="联系方式" prop="contact">
          <el-input v-model="form.contact" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="商铺类型的id" prop="typeId">
          <el-input v-model="form.typeId" placeholder="请输入商铺类型的id" />
        </el-form-item>
        <el-form-item label="商铺图片，多个图片以','隔开" prop="images">
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :on-success="handleAvatarSuccess"
            :http-request="uploadRequest"
            accept="image/*"
          >
            <img v-if="getValidAvatar(form.images)" :src="getValidAvatar(form.images)" class="avatar" @error="e => e.target.src = require('@/assets/images/profile.jpg')" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="评分，1~5分，乘10保存，避免小数" prop="score">
          <el-input v-model="form.score" placeholder="请输入评分，1~5分，乘10保存，避免小数" />
        </el-form-item>
        <el-divider content-position="center">房屋管理信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddTbHouse">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteTbHouse">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="tbHouseList" :row-class-name="rowTbHouseIndex" @selection-change="handleTbHouseSelectionChange" ref="tbHouse">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="房间标题" prop="title" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.title" placeholder="请输入房间标题" />
            </template>
          </el-table-column>
          <el-table-column label="副标题" prop="subTitle" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.subTitle" placeholder="请输入副标题" />
            </template>
          </el-table-column>
          <el-table-column label="折扣金额" prop="currentPrice" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.currentPrice" placeholder="请输入折扣金额" />
            </template>
          </el-table-column>
          <el-table-column label="原价" prop="originalPrice" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.originalPrice" placeholder="请输入原价" />
            </template>
          </el-table-column>
          <el-table-column label="0,整租；1,合租" prop="type" width="150">
            <template slot-scope="scope">
              <el-select v-model="scope.row.type" placeholder="请选择0,整租；1,合租">
                <el-option label="请选择字典生成" value="" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="1,上架; 2,下架; 3,过期" prop="status" width="150">
            <template slot-scope="scope">
              <el-select v-model="scope.row.status" placeholder="请选择1,上架; 2,下架; 3,过期">
                <el-option label="请选择字典生成" value="" />
              </el-select>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listOwner, getOwner, delOwner, addOwner, updateOwner } from "@/api/system/owner"
import { uploadFile } from '@/api/file'

export default {
  name: "Owner",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedTbHouse: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 房东管理表格数据
      ownerList: [],
      // 房屋管理表格数据
      tbHouseList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        contact: null,
        typeId: null,
        images: null,
        score: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "商铺名称不能为空", trigger: "blur" }
        ],
        typeId: [
          { required: true, message: "商铺类型的id不能为空", trigger: "blur" }
        ],
        images: [
          { required: true, message: "商铺图片，多个图片以','隔开不能为空", trigger: "blur" }
        ],
        score: [
          { required: true, message: "评分，1~5分，乘10保存，避免小数不能为空", trigger: "blur" }
        ],
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询房东管理列表 */
    getList() {
      this.loading = true
      listOwner(this.queryParams).then(response => {
        this.ownerList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        contact: null,
        typeId: null,
        images: null,
        score: null,
        createTime: null,
        updateTime: null
      }
      this.tbHouseList = []
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加房东管理"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getOwner(id).then(response => {
        this.form = response.data
        this.tbHouseList = response.data.tbHouseList
        this.open = true
        this.title = "修改房东管理"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.tbHouseList = this.tbHouseList
          if (this.form.id != null) {
            updateOwner(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addOwner(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除房东管理编号为"' + ids + '"的数据项？').then(function() {
        return delOwner(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
	/** 房屋管理序号 */
    rowTbHouseIndex({ row, rowIndex }) {
      row.index = rowIndex + 1
    },
    /** 房屋管理添加按钮操作 */
    handleAddTbHouse() {
      let obj = {}
      obj.title = ""
      obj.subTitle = ""
      obj.description = ""
      obj.currentPrice = ""
      obj.originalPrice = ""
      obj.type = ""
      obj.status = ""
      obj.images = ""
      this.tbHouseList.push(obj)
    },
    /** 房屋管理删除按钮操作 */
    handleDeleteTbHouse() {
      if (this.checkedTbHouse.length == 0) {
        this.$modal.msgError("请先选择要删除的房屋管理数据")
      } else {
        const tbHouseList = this.tbHouseList
        const checkedTbHouse = this.checkedTbHouse
        this.tbHouseList = tbHouseList.filter(function(item) {
          return checkedTbHouse.indexOf(item.index) == -1
        })
      }
    },
    /** 复选框选中数据 */
    handleTbHouseSelectionChange(selection) {
      this.checkedTbHouse = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/owner/export', {
        ...this.queryParams
      }, `owner_${new Date().getTime()}.xlsx`)
    },
    getValidAvatar(url) {
      if (!url) return require('@/assets/images/profile.jpg');
      if (url.includes(',')) url = url.split(',')[0];
      if (url.startsWith('https://placekitten.com/')) {
        return require('@/assets/images/profile.jpg');
      }
      return url;
    },
    uploadRequest({ file, onProgress, onSuccess, onError }) {
      uploadFile(file)
        .then(res => {
          if ((res.code === 0 || res.code === 200) && res.data && res.data.url) {
            onSuccess(res.data, file)
            this.form.images = res.data.url
          } else {
            onError(new Error('上传失败：' + res.msg))
          }
        })
        .catch(err => {
          onError(err)
        })
    },
    handleAvatarSuccess(res, file) {
      if (res && res.url) {
        this.form.images = res.url
      }
    },
    beforeAvatarUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt10M = file.size / 1024 / 1024 < 10
      if (!isImage) {
        this.$message.error('只能上传图片文件!')
      }
      if (!isLt10M) {
        this.$message.error('上传图片大小不能超过 10MB!')
      }
      return isImage && isLt10M
    },
  }
}
</script>
